
#include <iostream>
#include "mqtt.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include "link.h"
#include "json-c/json.h"
#include "database.h"
#include <unistd.h>
#include <time.h>
using namespace std;

int parse_type(unsigned char tt)
{


      return tt&0xf0;


}

void mqtt_connect(int fd,const char*buffer)
 {

   //printf("剩余长度 %d\n",buffer[1]);
   // printf("协议名称 %s\n",&buffer[4]); 
   unsigned char back[64]={0};

   back[0]=CONNACK;
   back[1]=0x02;
   back[2]=0x00;
   back[3]=0x00;

  if(send(fd,back,4,0)<0)
  {
        cout<<"connack fail..."<<endl;
  }

 }


  void mqtt_subscribe(int fd,const char*buffer)
  {

//    for(int i=0;i<11;i++)
//    {
//     printf("%x ",buffer[i]);
//    }
//    printf("\n");
      printf("[SUBSCRIBE]");
      char MSB=buffer[2];
      char LSB=buffer[3];
      char back[32]={0};
      short topiclen=buffer[5];
      
      memcpy(back,&buffer[6],topiclen);

      printf("主题长度为：%d 主题为%s\n",topiclen,back);

       unsigned char ret[64]={0};
    
      ret[0]=SUBACK;
      ret[1]=0x03;
      ret[2]=MSB;
      ret[3]=LSB;
      ret[4]=0x00;
      if(send(fd,ret,5,0)<0)
  {
        cout<<"suback fail..."<<endl;
  }


     add_link(fd,back);

     if(strstr(back,"upload"))
     {
         return ;


     }

     sleep(1);

      time_t t=time(NULL);
      struct json_object *obj=json_object_new_object();
      json_object_object_add(obj,"cmd",json_object_new_string("date"));
      json_object_object_add(obj,"time",json_object_new_int(t));
      const char* msg=json_object_to_json_string(obj);
       cout<<"返回了"<<endl;
       real_publish(back,msg,strlen(msg));
       cout<<msg<<endl;
      json_object_put(obj);


  //当有客户端订阅的话，就把该订阅放入链表中，等到发布去该链表中去找
     
  }


  void   mqtt_publish(int fd,const char*buffer)
  {

//    for(int i=0;i<20;i++)
//    {

//     printf("%x ",buffer[i]);
//    }
//     printf("\n");

      printf("[PUBLISH]");
      int remain=buffer[1];
      int topiclen=((short)buffer[2]<<8)+buffer[3];
      char msg[256]={0};
      char topic[32]={0};
      memcpy(topic,&buffer[4],topiclen);
      memcpy(msg,&buffer[2+2+topiclen],remain-topiclen);
      printf("主题名 %s 内容为%s\n",topic,msg);
      
      real_publish(topic,msg,remain-topiclen-2);

  }

  void notify(int fd,const char*topic,const char*msg,int msglen)
  {
      char buffer[512]={0};
      int index=0;
      int topiclen=strlen(topic);
      buffer[index++]=PUBLISH;
      buffer[index++]=2+topiclen+msglen;
      buffer[index++]=0;
      buffer[index++]=topiclen;
      memcpy(&buffer[index],topic,topiclen);
      index+=topiclen;
      memcpy(&buffer[index],msg,msglen);
      //index+=msglen;
     // buffer[index]=0x00;

      printf("%s\n",msg);
      if(send(fd,buffer,4+topiclen+msglen,0)<0)
      {
         cout<<"send fail..."<<endl;
      }
     

  }


  void mqtt_register(int fd,const char* buffer)
  {
      struct json_object*obj=json_tokener_parse(buffer+1);
      if(NULL==obj)
      {

        printf("[ERROR] Not JSON OBJECT\n");
        return ;

      }
 
      struct json_object*value;
      json_object_object_get_ex(obj,"username",&value);  //解析username
      const char* username=json_object_get_string(value);
      json_object_object_get_ex(obj,"password",&value);   //解析password
      const char* password=json_object_get_string(value);

      if(sqlite3_user_exist(username))
      {
        cout<<"注册失败"<<endl;
        struct  json_object*replyobject=json_object_new_object();
        json_object_object_add(replyobject,"cmd",json_object_new_string("register"));
        json_object_object_add(replyobject,"result",json_object_new_string("exist"));
        const char* SendString=json_object_to_json_string(replyobject);
        
        if(send(fd,SendString,strlen(SendString),0)<0)
        {cout<<"发送失败"<<endl;}

          json_object_put(replyobject);


      }
      else
      {

        cout<<"注册成功"<<endl;
        sqlite3_insert(username,password);
           struct  json_object*replyobject=json_object_new_object();
        json_object_object_add(replyobject,"cmd",json_object_new_string("register"));
        json_object_object_add(replyobject,"result",json_object_new_string("success"));
        const char* SendString=json_object_to_json_string(replyobject);
        
        if(send(fd,SendString,strlen(SendString),0)<0)
        {cout<<"发送失败"<<endl;}

         
          json_object_put(replyobject);





      }

      json_object_put(obj);

  }

  void mqtt_login(int fd,const char* buffer)
{
      struct json_object*obj=json_tokener_parse(buffer+1);
      if(NULL==obj)
      {

        printf("[ERROR] Not JSON OBJECT\n");
        return ;

      }
 
      struct json_object*value;
      json_object_object_get_ex(obj,"username",&value);  //解析username
      const char* username=json_object_get_string(value);
      json_object_object_get_ex(obj,"password",&value);   //解析password
      const char* password=json_object_get_string(value);

        if(!sqlite3_user_exist(username))
      {
       
        struct  json_object*replyobject=json_object_new_object();
        json_object_object_add(replyobject,"cmd",json_object_new_string("login"));
        json_object_object_add(replyobject,"result",json_object_new_string("usernoexist"));
        const char* SendString=json_object_to_json_string(replyobject);
        
        if(send(fd,SendString,strlen(SendString),0)<0)
        {cout<<"发送失败"<<endl;}

          json_object_put(replyobject);


      }

      else
      {
          if(sqlite3_login_comp(username,password))
          {
                struct  json_object*replyobject=json_object_new_object();
            json_object_object_add(replyobject,"cmd",json_object_new_string("login"));
           json_object_object_add(replyobject,"result",json_object_new_string("success"));
           const char* SendString=json_object_to_json_string(replyobject);
        
        if(send(fd,SendString,strlen(SendString),0)<0)
        {cout<<"发送失败"<<endl;}

          json_object_put(replyobject);
            

          }
          else
          {

             struct  json_object*replyobject=json_object_new_object();
            json_object_object_add(replyobject,"cmd",json_object_new_string("login"));
           json_object_object_add(replyobject,"result",json_object_new_string("passworderr"));
           const char* SendString=json_object_to_json_string(replyobject);
        
        if(send(fd,SendString,strlen(SendString),0)<0)
               {cout<<"发送失败"<<endl;}

          json_object_put(replyobject);






          }









      }






}
